/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package cn.lang.auth.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.lang.auth.common.manager.CacheManager;
import cn.lang.auth.common.utils.jwt.JwtUtil;
import cn.lang.auth.common.utils.ret.CodeMsg;
import cn.lang.auth.common.utils.ret.Ret;
import cn.lang.auth.pojo.dto.SysUserDto;
import cn.lang.auth.pojo.entity.SysUserEntity;
import cn.lang.auth.pojo.vo.LoginUserVo;
import cn.lang.auth.pojo.vo.UserTokenVo;
import cn.lang.auth.service.IRoleService;
import cn.lang.auth.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

/**
* @title: SysLoginController
* @description: 登录相关
* @author: Lang 1102076808@qq.com
* @date: 2020/6/18 23:36
*/
@RestController
public class SysLoginController {

	@Autowired
	private IUserService userService;

	@Autowired
	private IRoleService roleService;
	/**
	 * 登录
	 */
	@RequestMapping("/sys/login")
	public Ret login(@RequestBody LoginUserVo loginUserVo){
		/** 登录认证*/
		SysUserEntity userEntity = userService.getByUsername(loginUserVo.getUsername());
		if(ObjectUtil.isEmpty(userEntity)){
			return Ret.error(CodeMsg.SERVER_LOGIN_ERROR.fillArgs("未找到该用户"));
		}
		/** 缓存用户信息与权限*/
		Set<String> userPermissions = roleService.getUserPermissions(userEntity.getUserId());
		SysUserDto sysUserDto = new SysUserDto();
		sysUserDto.setSysUserEntity(userEntity);
		sysUserDto.setPerms(userPermissions);
		CacheManager.putUser(userEntity.getUserId(),sysUserDto);

		/** 返回用户信息与token*/
		UserTokenVo userTokenVo = new UserTokenVo();
		String token = JwtUtil.generateToken(userEntity.getUserId().toString());
		userTokenVo.setToken(token);
		userTokenVo.setSysUserEntity(userEntity);
		return Ret.success(userTokenVo);
	}

	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public Ret logout() {
		return Ret.success(CodeMsg.SUCCESS);
	}
	
}
